<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="formRef" :model="user" labelWidth="80px">
        <uni-forms-item label="用户头像" name="avatar">
          <view class="avatar">
            <img @click="selectAvatar" :src="avatarUrl" alt="">
          </view>
        </uni-forms-item>
        <uni-forms-item label="用户昵称" name="nickName">
          <uni-easyinput v-model="user.username" placeholder="请输入昵称" />
        </uni-forms-item>
        <uni-forms-item label="手机号码" name="phonenumber">
          <uni-easyinput v-model="user.phonenumber" placeholder="请输入手机号码" />
        </uni-forms-item>
        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
        </uni-forms-item>
        <uni-forms-item label="性别" name="sex" required>
          <uni-data-checkbox v-model="user.sex" :localdata="sexs" />
        </uni-forms-item>
      </uni-forms>
      <button type="primary" @click="submit">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getUserProfile } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import { getUserInfo, editUserInfo } from "@/api/user/index";
import config from '@/config'

const baseUrl = config.baseUrl

const userStore = useUserStore()
// 创建响应式数据
const formRef = ref(null);
const user = reactive({
  username: "",
  phonenumber: "",
  email: "",
  sex: ""
});
const avatarUrl = ref('');
const sexs = [
  {
    text: '男',
    value: "0"
  },
  {
    text: '女',
    value: "1"
  }
];
const rules = {
  username: {
    rules: [
      {
        required: true,
        errorMessage: '用户昵称不能为空'
      }
    ]
  },
  phonenumber: {
    rules: [
      {
        required: false,
        errorMessage: '手机号码不能为空'
      },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        errorMessage: '请输入正确的手机号码'
      }
    ]
  },
  email: {
    rules: [
      {
        required: false,
        errorMessage: '邮箱地址不能为空'
      },
      {
        format: 'email',
        errorMessage: '请输入正确的邮箱地址'
      }
    ]
  }
};

/**
 * 动态导入默认头像
 */
const loadDefaultAvatar = async () => {
  if (!userStore.userInfo.avatar) {
    try {
      const module = await import('@/assets/mine/defautAvatar.svg');
      avatarUrl.value = module.default;
    } catch (error) {
      console.error('Failed to load image:', error);
    }
  } else {
    avatarUrl.value = userStore.userInfo.avatar;
  }

};

/**
 * 获取用户信息
 */
const getUser = async () => {
  try {
    user.username = userStore.userInfo.username
    user.phonenumber = userStore.userInfo.phonenumber
    user.email = userStore.userInfo.email
    user.sex = userStore.userInfo.sex
  } catch (error) {
    console.error('Failed to get user profile:', error);
  }
};

/**
 * 提交表单
 */
const submit = async () => {
  uploadAvatar()
  try {
    await formRef.value.validate();
    editUserInfo({ ...user, userId: userStore.userId }).then(res => {
      if (res.code == 200) {
        uni.showToast({
          title: '修改成功',
          mask: false,
          duration: 1000
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      } else {
        uni.showToast({
          title: res.message || '网络开了点小差, 请稍后再试~',
          mask: false,
          icon: 'error',
          duration: 1000
        });
      }
    }).catch(err => {
      uni.showToast({
        title: err || '网络开了点小差, 请稍后再试~',
        icon: 'error',
        mask: false,
        duration: 1000
      });
    })

  } catch (error) {
    console.error('Form validation failed:', error);
  }
};

const selectUrl = ref(''); // 重新选择的头像
// 选择头像处理函数
const selectAvatar = () => {
  uni.chooseImage({
    count: 1, // 限制选择一张图片
    sizeType: ["original", "compressed"], // 可以选择原图或压缩图
    sourceType: ["album", "camera"], // 从相册或相机选择
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]; // 获取选择的图片临时路径
      selectUrl.value = tempFilePath;
      avatarUrl.value = tempFilePath
      console.log('avatarUrl.value: ', avatarUrl.value);
    },
    fail: (err) => {
      console.error("选择头像失败：", err);
    }
  });
};

// 上传头像的方法
const uploadAvatar = () => {
  if (!selectUrl.value) {
    return
  }
  uni.uploadFile({
    url: baseUrl + '/users/upload/avatar',
    filePath: selectUrl.value,
    name: 'file', // 字段名必须与后端一致
    formData: {
      userId: userStore.userId,
    },
    success: (uploadRes) => {
      console.log('uploadRes: ', uploadRes);
      const res = JSON.parse(uploadRes.data); // 解析返回的数据
      if (res.code == '200') {
        console.log('头像上传成功,URL:', res.path);
        selectUrl.value = res.path; // 更新头像地址
        getUserInfo({ userId: userStore.userId }).then(res => {
          userStore.getInfo(res.userInfo)
        })
      } else {
        console.error('头像上传失败：', res.message);
      }
    },
    fail: (err) => {
      console.error('头像上传失败：', err);
    },
  });
};

// 生命周期钩子
onMounted(async () => {
  await getUser();
  await loadDefaultAvatar();
  formRef.value.setRules(rules);
});

</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

.example {
  padding: 30rpx;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 30rpx;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 70rpx;
  line-height: 70rpx;
  margin-left: 20rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx solid #edf2fa;
  border-radius: 50%;

  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
</style>